import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken,getUserId, removeToken,setUserId } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}


const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {


 // user login
 login({ commit }, userInfo) {
  const { username, password ,captcha,codeEncryption} = userInfo
  return new Promise((resolve, reject) => {
    login({ urUsername: username.trim(), urPassword: password ,captcha:captcha,codeEncryption:codeEncryption}).then(response => {
      const { data } = response
      if(data.msg){
        resolve(data.msg)
      }
      commit('SET_TOKEN', data.token.tokenValue)
      setToken(data.token.tokenValue)
      setUserId(data.userId)
      resolve()
    }).catch(error => {
      reject(error)
    })
  })
},

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(getUserId()).then(response => {
        const { user } = response.data
        if (!user) {
          return reject('Verification failed, please Login again.')
        }
        const { urUsername, urAvatar } = user
        commit('SET_NAME', urUsername)
        commit('SET_AVATAR', urAvatar)
        resolve(user)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(getUserId()).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

